﻿using System;

namespace Silver3D.Graphics
{
    public abstract class EntityInstance : SceneObject
    {
        public Node Parent { get; internal set; }
        public Entity Entity { get; private set; }

        private static string CreateId(Entity entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");
            return entity.Id + "Instance";
        }

        public EntityInstance(Scene scene, string id, Entity entity)
            : this(scene, id, entity, null)
        {
        }

        public EntityInstance(Scene scene, Entity entity, Node parent)
            : this(scene, CreateId(entity), entity, parent)
        {
        }

        public EntityInstance(Scene scene, string id, Entity entity, Node parent)
            : base(scene, id)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            Entity = entity;
            Entity.Detached += new ObjectDetachedHandler(OnEntityDetached);

            if (parent != null)
            {
                parent.AddInstance(this);
            }
        }

        private void OnEntityDetached(SceneObject obj)
        {
            if (obj != Entity) return;
            this.Detach();
            Entity = null;
        }

        public override void Detach()
        {
            if (Parent != null) Parent.RemoveInstance(this);
            base.Detach();
        }
    }
}
